#接入deepseek并且设置界面

import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext, filedialog
import requests
import json
import threading
import os

class ModernChatApp:
    def __init__(self, root):
        self.root = root
        self.root.title("🤖 AI 聊天助手")
        self.root.geometry("1200x800")
        self.root.configure(bg='#1e1e1e')
        self.root.minsize(800, 600)
        
        # 配置
        self.api_config = {
            "api_key": "sk-9f407fd69c17440682d5dcf16edab91b",
            "api_url": "https://api.deepseek.com/v1/chat/completions",
            "model_name": "deepseek-chat"
        }
        
        # 系统提示词
        self.system_prompt = "你是一个有用的AI助手。"
        
        # 聊天历史
        self.chat_history = []
        
        # 设置样式
        self.setup_styles()
        
        # 创建界面
        self.create_widgets()
        
        # 添加欢迎消息
        self.add_message("系统", "🎉 欢迎使用全新的AI聊天助手！")
        self.add_message("系统", "💡 提示: 按 Ctrl+Enter 发送消息，Shift+Enter 换行")
        
    def setup_styles(self):
        """设置现代化样式"""
        self.colors = {
            'bg_dark': '#1e1e1e',
            'bg_mid': '#2d2d2d',
            'bg_light': '#3d3d3d',
            'accent': '#007acc',
            'accent_hover': '#005a9e',
            'text_primary': '#ffffff',
            'text_secondary': '#cccccc',
            'user_msg': '#007acc',
            'ai_msg': '#4ade80',
            'border': '#555555'
        }
        
    def create_widgets(self):
        """创建主界面"""
        # 主框架
        main_frame = tk.Frame(self.root, bg=self.colors['bg_dark'])
        main_frame.pack(fill=tk.BOTH, expand=True, padx=15, pady=15)
        
        # 标题栏
        self.create_header(main_frame)
        
        # 聊天区域
        self.create_chat_area(main_frame)
        
        # 输入区域
        self.create_input_area(main_frame)
        
        # 状态栏
        self.create_status_bar(main_frame)
        
    def create_header(self, parent):
        """创建标题栏"""
        header = tk.Frame(parent, bg=self.colors['bg_mid'])
        header.pack(fill=tk.X, pady=(0, 15))
        
        # 标题
        title = tk.Label(
            header, 
            text="🤖 AI 聊天助手",
            font=('Segoe UI', 18, 'bold'),
            bg=self.colors['bg_mid'],
            fg=self.colors['text_primary']
        )
        title.pack(side=tk.LEFT, padx=20, pady=15)
        
        # 操作按钮
        btn_frame = tk.Frame(header, bg=self.colors['bg_mid'])
        btn_frame.pack(side=tk.RIGHT, padx=20)
        
        # 新建聊天按钮
        new_btn = tk.Button(
            btn_frame,
            text="➕ 新建聊天",
            command=self.new_chat_window,
            bg=self.colors['accent'],
            fg='white',
            font=('Segoe UI', 11, 'bold'),
            borderwidth=0,
            relief='flat',
            cursor='hand2',
            activebackground=self.colors['accent_hover'],
            padx=20,
            pady=8
        )
        new_btn.pack(side=tk.LEFT, padx=5)
        
        # 加载人设按钮
        load_btn = tk.Button(
            btn_frame,
            text="👤 加载人设",
            command=self.load_persona,
            bg='#ff6b6b',
            fg='white',
            font=('Segoe UI', 11, 'bold'),
            borderwidth=0,
            relief='flat',
            cursor='hand2',
            activebackground='#ff5252',
            padx=20,
            pady=8
        )
        load_btn.pack(side=tk.LEFT, padx=5)
        
        # 清空按钮
        clear_btn = tk.Button(
            btn_frame,
            text="🧹 清空",
            command=self.clear_chat,
            bg=self.colors['bg_light'],
            fg=self.colors['text_primary'],
            font=('Segoe UI', 11),
            borderwidth=0,
            relief='flat',
            cursor='hand2',
            activebackground=self.colors['border'],
            padx=20,
            pady=8
        )
        clear_btn.pack(side=tk.LEFT, padx=5)
        
    def create_chat_area(self, parent):
        """创建聊天显示区域"""
        # 聊天容器
        chat_container = tk.Frame(parent, bg=self.colors['bg_mid'])
        chat_container.pack(fill=tk.BOTH, expand=True, pady=(0, 15))
        
        # 聊天显示
        self.chat_display = scrolledtext.ScrolledText(
            chat_container,
            wrap=tk.WORD,
            font=('Segoe UI', 12),
            bg=self.colors['bg_mid'],
            fg=self.colors['text_primary'],
            insertbackground=self.colors['text_primary'],
            relief='flat',
            borderwidth=0,
            padx=20,
            pady=15
        )
        self.chat_display.pack(fill=tk.BOTH, expand=True)
        
        # 配置标签样式
        self.chat_display.tag_configure('user', foreground=self.colors['user_msg'], 
                                      font=('Segoe UI', 12, 'bold'))
        self.chat_display.tag_configure('ai', foreground=self.colors['ai_msg'], 
                                      font=('Segoe UI', 12, 'bold'))
        self.chat_display.tag_configure('system', foreground=self.colors['text_secondary'], 
                                      font=('Segoe UI', 11, 'italic'))
        
        # 禁用编辑
        self.chat_display.config(state=tk.DISABLED)
        
    def create_input_area(self, parent):
        """创建输入区域"""
        # 输入容器
        input_container = tk.Frame(parent, bg=self.colors['bg_light'])
        input_container.pack(fill=tk.X, pady=(0, 15))
        
        # 输入框
        self.message_entry = tk.Text(
            input_container,
            height=3,
            font=('Segoe UI', 13),
            bg=self.colors['bg_light'],
            fg=self.colors['text_primary'],
            insertbackground=self.colors['text_primary'],
            relief='flat',
            borderwidth=0,
            padx=15,
            pady=15
        )
        self.message_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=15, pady=15)
        
        # 发送按钮
        send_btn = tk.Button(
            input_container,
            text="📤 发送",
            command=self.send_message,
            bg=self.colors['accent'],
            fg='white',
            font=('Segoe UI', 13, 'bold'),
            borderwidth=0,
            relief='flat',
            cursor='hand2',
            activebackground=self.colors['accent_hover'],
            padx=30,
            pady=10
        )
        send_btn.pack(side=tk.RIGHT, padx=15, pady=15)
        
        # 绑定快捷键
        self.message_entry.bind('<Control-Return>', lambda e: self.send_message())
        self.message_entry.bind('<Shift-Return>', lambda e: None)
        
        # 设置焦点
        self.message_entry.focus_set()
        
    def create_status_bar(self, parent):
        """创建状态栏"""
        status_frame = tk.Frame(parent, bg=self.colors['bg_mid'])
        status_frame.pack(fill=tk.X)
        
        self.status_label = tk.Label(
            status_frame,
            text="✅ 准备就绪",
            font=('Segoe UI', 11),
            bg=self.colors['bg_mid'],
            fg=self.colors['text_secondary']
        )
        self.status_label.pack(side=tk.LEFT, padx=20, pady=10)
        
    def add_message(self, sender, message):
        """添加消息到聊天"""
        self.chat_display.config(state=tk.NORMAL)
        
        if sender == "用户":
            self.chat_display.insert(tk.END, f"👤 你: ", 'user')
            self.chat_display.insert(tk.END, f"{message}\n\n")
        elif sender == "助手":
            self.chat_display.insert(tk.END, f"🤖 AI: ", 'ai')
            self.chat_display.insert(tk.END, f"{message}\n\n")
        else:
            self.chat_display.insert(tk.END, f"ℹ️ {message}\n\n", 'system')
            
        self.chat_display.config(state=tk.DISABLED)
        self.chat_display.see(tk.END)
        self.chat_history.append({"sender": sender, "message": message})
        
    def send_message(self):
        """发送消息"""
        message = self.message_entry.get("1.0", tk.END).strip()
        if not message:
            messagebox.showwarning("⚠️ 提示", "请输入要发送的消息！")
            return
            
        self.add_message("用户", message)
        self.message_entry.delete("1.0", tk.END)
        
        # 更新状态
        self.status_label.config(text="🔄 正在发送...")
        
        # 在新线程中发送请求
        threading.Thread(target=self.send_api_request, args=(message,), 
                        daemon=True).start()
        
    def send_api_request(self, message):
        """发送API请求"""
        try:
            headers = {
                'Content-Type': 'application/json',
                'Authorization': f'Bearer {self.api_config["api_key"]}'
            }
            
            data = {
                "model": self.api_config["model_name"],
                "messages": [
                    {"role": "system", "content": self.system_prompt},
                    {"role": "user", "content": message}
                ],
                "max_tokens": 2000,
                "temperature": 0.7
            }
            
            response = requests.post(
                self.api_config["api_url"],
                headers=headers,
                json=data,
                timeout=30
            )
            
            if response.status_code == 200:
                result = response.json()
                assistant_message = result['choices'][0]['message']['content']
                self.root.after(0, lambda: self.add_message("助手", assistant_message))
                self.root.after(0, lambda: self.status_label.config(text="✅ 回复成功"))
            else:
                error_msg = f"❌ API错误: {response.status_code}"
                self.root.after(0, lambda: self.add_message("系统", error_msg))
                self.root.after(0, lambda: self.status_label.config(text="❌ 请求失败"))
                
        except requests.exceptions.Timeout:
            self.root.after(0, lambda: self.add_message("系统", "⏰ 请求超时，请检查网络连接"))
            self.root.after(0, lambda: self.status_label.config(text="⏰ 请求超时"))
        except Exception as e:
            self.root.after(0, lambda: self.add_message("系统", f"⚠️ 发生错误: {str(e)}"))
            self.root.after(0, lambda: self.status_label.config(text="⚠️ 发生错误"))
            
    def clear_chat(self):
        """清空聊天内容"""
        self.chat_display.config(state=tk.NORMAL)
        self.chat_display.delete(1.0, tk.END)
        self.chat_display.config(state=tk.DISABLED)
        self.chat_history.clear()
        self.status_label.config(text="🧹 已清空聊天记录")
        
    def load_persona(self):
        """加载人设提示词文件"""
        file_path = filedialog.askopenfilename(
            title="选择人设提示词文件",
            filetypes=[
                ("文本文件", "*.txt"),
                ("所有文件", "*.*")
            ],
            initialdir=os.path.expanduser("~")
        )
        
        if file_path:
            try:
                with open(file_path, 'r', encoding='utf-8') as file:
                    persona_content = file.read().strip()
                    
                if persona_content:
                    self.system_prompt = persona_content
                    self.add_message("系统", f"✅ 已成功加载人设提示词：{os.path.basename(file_path)}")
                    self.status_label.config(text=f"👤 当前人设：{os.path.basename(file_path)}")
                else:
                    messagebox.showwarning("⚠️ 警告", "文件内容为空，未更改人设提示词")
                    
            except Exception as e:
                messagebox.showerror("❌ 错误", f"无法读取文件：{str(e)}")
        
    def new_chat_window(self):
        """创建新的聊天窗口"""
        new_window = tk.Toplevel(self.root)
        new_app = ModernChatApp(new_window)
        new_window.title("🤖 AI 助手 - 新窗口")
        new_window.geometry("1200x800")
        new_window.focus_force()

def main():
    """主函数"""
    root = tk.Tk()
    app = ModernChatApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()